from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response

from shipwreck.main.models import *
from google.appengine.api import users
from google.appengine.ext.db import djangoforms
from django import newforms as forms
from shipwreck.main.helpers import *


import logging
from datetime import datetime
    
def getUserData():
    current_user = users.get_current_user()
    character = Character.all().filter('owner = ', current_user).get()
    current_user.character = character
    character.calculateActions()
    return current_user

class CreateCharacterForm(djangoforms.ModelForm):
    class Meta:
        model = Character
        fields = ['name', 'sex']

def frontpage(request):
    current_user = users.get_current_user()
    character = Character.all().filter('owner = ', current_user).get()
    if character:
        current_user.character = character
        logging.info("Character from database is "+str(character.name))
        character.calculateActions()
        return render_to_response('index.html', {'user': current_user, 'char': character, 'map': character.surroundings_as_html(size_x=2, size_y=2)}) 
    else:
        return HttpResponseRedirect('/create')

def map(request):
    user = getUserData()
    zone = user.character.zone
    (x,y) = user.character.x,user.character.y
    return render_to_response('map.html', { 'user': user, 'char': user.character, 'map': user.character.surroundings_as_html(size_x=5, size_y=5) })


def create_character(request):
    if request.method == 'POST':
        form = CreateCharacterForm(request.POST)
        if form.is_valid():

            character = form.save(commit=False)
            character.number = getNextNumberFor(Character)
            character.owner = users.get_current_user()
            zone = Zone.all().filter("number =",1).get()
            character.setRandomStartingPosition(zone)
            # calculateActions automatically puts the character into the database
            character.calculateActions()
            return HttpResponseRedirect('/')
    else:
        form = CreateCharacterForm()
    return render_to_response('create_character.html', {'form': form})

def moveto(request, zone, x, y):
    user = getUserData()
    """ Check terrain is potential landing point """
    z = Zone.all().filter("number =",int(zone)).get()
    logging.info("MoveTo request to go to %s,%s,%s which is in zone %s" % (zone,x,y,z))
    terrain = z.getTerrainAtGlobal((x,y))
    logging.info("MoveTo target terrain is %s" % (str(terrain)))
    if terrain and terrain.passable and user.character.actions >= terrain.cost:
        user.character.moveto(z,int(x),int(y), terrain)
    return HttpResponseRedirect('/')
    
def rest(request):
    user = getUserData()
    user.character.wait()
    return HttpResponseRedirect('/')

def hunt(request):
    user = getUserData()
    zone = user.character.zone
    """ See if any monsters are in this area """
    monster = CreaturePrototype.findRandomCreatureForLocation((user.character.x,user.character.y),zone)
    results = user.character.battle(monster)
    return render_to_response('hunt.html', {'monster': monster, 'user':user, 'char':user.character, 'results': results})
